package io.youngledo.usb.task;

import javafx.concurrent.Task;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.function.Consumer;

/**
 * 存储任务基类 - 使用Java 21 record和现代化特性
 */
public class StorageTask extends Task<Void> {

    private final String taskId;
    private final TaskType taskType;
    private final String description;
    private final Callable<Void> operation;
    private final ProgressTracker progressTracker;
    private final LocalDateTime createdTime;

    // 任务元数据
    private final String connectionId;
    private final String bucketName;
    private final List<String> targetFiles;

    // 回调函数
    private Consumer<StorageTask> onTaskCompleted;
    private Consumer<StorageTask> onTaskFailed;
    private Consumer<StorageTask> onTaskCancelled;

    public StorageTask(String taskId, TaskType taskType, String description,
                      String connectionId, String bucketName, List<String> targetFiles,
                      Callable<Void> operation, ProgressTracker progressTracker) {
        this.taskId = taskId;
        this.taskType = taskType;
        this.description = description;
        this.connectionId = connectionId;
        this.bucketName = bucketName;
        this.targetFiles = targetFiles != null ? List.copyOf(targetFiles) : List.of();
        this.operation = operation;
        this.progressTracker = progressTracker;
        this.createdTime = LocalDateTime.now();

        // 设置JavaFX Task的属性
        updateTitle(description);
        updateMessage("准备中...");
    }

    @Override
    protected Void call() throws Exception {
        // 设置当前任务到线程本地存储
        TaskManager.getInstance().setCurrentTask(this);

        try {
            updateMessage("执行中...");
            progressTracker.resume(); // 确保进度跟踪器处于活动状态

            // 执行实际操作
            operation.call();

            // 标记完成
            progressTracker.complete();
            updateMessage("完成");

            // 触发完成回调
            if (onTaskCompleted != null) {
                onTaskCompleted.accept(this);
            }

            return null;
        } catch (Exception e) {
            // 标记失败
            progressTracker.fail(e.getMessage());
            updateMessage("失败: " + e.getMessage());

            // 触发失败回调
            if (onTaskFailed != null) {
                onTaskFailed.accept(this);
            }

            throw e;
        } finally {
            // 清理线程本地存储
            TaskManager.getInstance().clearCurrentTask();
        }
    }

    @Override
    protected void cancelled() {
        super.cancelled();
        progressTracker.cancel();
        updateMessage("已取消");

        if (onTaskCancelled != null) {
            onTaskCancelled.accept(this);
        }
    }

    /**
     * 暂停任务
     */
    public void pause() {
        if (!isDone() && !isCancelled()) {
            progressTracker.pause();
            updateMessage("已暂停");
        }
    }

    /**
     * 恢复任务
     */
    public void resume() {
        if (!isDone() && !isCancelled()) {
            progressTracker.resume();
            updateMessage("恢复执行...");
        }
    }

    /**
     * 获取任务摘要信息
     */
    public TaskSummary getSummary() {
        return new TaskSummary(
            taskId,
            taskType,
            description,
            getTaskStatus(),
            progressTracker.getProgress(),
            createdTime,
            connectionId,
            bucketName,
            targetFiles.size()
        );
    }

    /**
     * 获取当前任务状态
     */
    public TaskStatus getTaskStatus() {
        if (isCancelled()) return TaskStatus.CANCELLED;
        if (isDone()) {
            return getException() != null ? TaskStatus.FAILED : TaskStatus.COMPLETED;
        }
        if (isRunning()) {
            return progressTracker.isPaused() ? TaskStatus.PAUSED : TaskStatus.RUNNING;
        }
        return TaskStatus.PENDING;
    }

    // Getters
    public String getTaskId() { return taskId; }
    public TaskType getTaskType() { return taskType; }
    public String getDescription() { return description; }
    public ProgressTracker getProgressTracker() { return progressTracker; }
    public LocalDateTime getCreatedTime() { return createdTime; }
    public String getConnectionId() { return connectionId; }
    public String getBucketName() { return bucketName; }
    public List<String> getTargetFiles() { return targetFiles; }

    // Callback setters
    public void setOnTaskCompleted(Consumer<StorageTask> callback) {
        this.onTaskCompleted = callback;
    }

    public void setOnTaskFailed(Consumer<StorageTask> callback) {
        this.onTaskFailed = callback;
    }

    public void setOnTaskCancelled(Consumer<StorageTask> callback) {
        this.onTaskCancelled = callback;
    }

    /**
     * 任务摘要记录 - 使用Java 21 record
     */
    public record TaskSummary(
        String taskId,
        TaskType taskType,
        String description,
        TaskStatus status,
        double progress,
        LocalDateTime createdTime,
        String connectionId,
        String bucketName,
        int fileCount
    ) {
        public String getFormattedProgress() {
            return String.format("%.1f%%", progress * 100);
        }

        public String getFormattedCreatedTime() {
            return createdTime.format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        }
    }
}